package com.ruoyi.web.controller.comment;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.client.domain.SysBuy;
import com.ruoyi.client.domain.SysSell;
import com.ruoyi.client.service.ISysBuyService;
import com.ruoyi.client.service.ISysSellService;
import com.ruoyi.common.annotation.Anonymous;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 前后端交互的类实现消息的接收推送(自己发送给自己)
 *
 * @ServerEndpoint(value = "/test/one") 前端通过此URI和后端交互，建立连接
 */
@Slf4j
@ServerEndpoint(value = "/test/one")
@Component
public class OneWebSocket {
    private int connectionCount = 0; // 连接计数变量
    private static ISysSellService iSysSellService;

    private static ISysBuyService iSysBuyService;
    @Autowired
    public void setiSysBuyService(ISysBuyService iSysBuyService) {
        OneWebSocket.iSysBuyService = iSysBuyService;
    }

    @Autowired
    public void setiSysSellService(ISysSellService iSysSellService) {
        OneWebSocket.iSysSellService = iSysSellService;
    }
    /**
     * 记录当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws JsonProcessingException, InterruptedException {
        connectionCount++; // 每次接收到消息，连接计数加 1
        System.err.println("websocket连接数:"+connectionCount);
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        // 解析消息内容，获取前端传过来的参数
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(message);
        String symbol = jsonNode.get("symbol").asText();
        System.err.println("jjjjjjj====="+symbol);
        String trade = jsonNode.get("trade").asText();
        // 根据参数处理业务逻辑并返回数据给客户端
        HashMap<String, Object> map = new HashMap<>();
        while (true){
            TimeUnit.SECONDS.sleep(1);
            List<SysSell> sellList = getSellList(symbol, trade);
            List<SysBuy> sysBuys = getBuyList(symbol,trade);
            map.put("sysBuys",sysBuys);
            map.put("sysSell",sellList);
            this.sendMessage(new ObjectMapper().writeValueAsString(map), session);
        }
    }
//  卖出
    public List<SysSell> getSellList(String symbol,String trade) throws JsonProcessingException {
        double num=Double.parseDouble(trade);
        List<SysSell> sellList = iSysSellService.sysSellList(symbol);
        final HashMap<String, Object> map = new HashMap<>();
        if(sellList.size()<=0) {
            for (int i = 1; i <= 5; i++) {
                SysSell sysSell = new SysSell();
                num += 0.01;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                String format = decimalFormat.format(num);
                System.err.println(format);
                sysSell.setSellPrice(format);
                Random random = new Random();
                sysSell.setHands(String.valueOf(random.nextInt(1001)));
                sysSell.setName("卖" + i);
                sysSell.setSymbol(symbol);
                iSysSellService.add(sysSell);
                sellList.add(sysSell);
            }
            return sellList;
        }
        return sellList;
    }
    //买入
    public List<SysBuy> getBuyList(String symbol,String trade){
        double num=Double.parseDouble(trade);
        num=num+0.01;
        List<SysBuy> sysBuys = iSysBuyService.sysBuyList(symbol);
        if(sysBuys.size()<=0){
            for (int i = 1; i <=5; i++) {
                SysBuy sysBuy = new SysBuy();
                num -=0.01;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                String format = decimalFormat.format(num);
                System.err.println(format);
                sysBuy.setName("买"+i);
                sysBuy.setBuyPrice(format);
                sysBuy.setSymbol(symbol);
                Random random = new Random();
                sysBuy.setHands(String.valueOf(random.nextInt(1001)));
                iSysBuyService.add(sysBuy);
                sysBuys.add(sysBuy);
            }
            return sysBuys;
        }
        return sysBuys;
    }





    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }
}